package repository

import (
	"context"
	"server_go/internal/model"
)

type AdiminRepository interface {
	GetAdiminByAccount(ctx context.Context, account string) (*model.Adimin, error)
	CreateUser(ctx context.Context, account string, password string, name string) (*model.Users, error)
	GetUserById(ctx context.Context, userId uint) (*model.Users, error)
	DeleteUser(ctx context.Context, userId uint) error
	ResetPassword(ctx context.Context, userId uint, password string) error
	QueryAllUser(ctx context.Context) ([]model.Users, error)
}

func NewAdiminRepository(
	repository *Repository,
) AdiminRepository {
	return &adiminRepository{
		Repository: repository,
	}
}

type adiminRepository struct {
	*Repository
}

// 根据account从数据库中获取管理员信息
func (r *adiminRepository) GetAdiminByAccount(ctx context.Context, account string) (*model.Adimin, error) {
	var adimin model.Adimin
	err := r.DB(ctx).Where("account = ? ", account).First(&adimin).Error
	if err != nil {
		return nil, err
	}
	return &adimin, nil
}
func (r *adiminRepository) CreateUser(ctx context.Context, account string, password string, name string) (*model.Users, error) {
	var users model.Users
	users.Account = account
	users.Name = name
	users.Password = password
	err := r.DB(ctx).Create(&users).Error
	if err != nil {
		return nil, err
	}
	return &users, nil
}
func (r *adiminRepository) GetUserById(ctx context.Context, userId uint) (*model.Users, error) {
	var user model.Users
	err := r.DB(ctx).Where("id = ? ", userId).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
func (r *adiminRepository) DeleteUser(ctx context.Context, userId uint) error {
	return r.DB(ctx).Where("id = ? ", userId).Delete(&model.Users{}).Error
}

// 重置密码
func (r *adiminRepository) ResetPassword(ctx context.Context, userId uint, password string) error {
	return r.DB(ctx).Model(&model.Users{}).Where("id = ? ", userId).Update("password", password).Error
}

func (r *adiminRepository) QueryAllUser(ctx context.Context) ([]model.Users, error) {
	var users []model.Users
	err := r.DB(ctx).Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}
